<?php

/**
 * ECSHOP 广告管理程序
 * ============================================================================
 * * 版权所有 2005-2012 上海商派网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.ecshop.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: liubo $
 * $Id: ads.php 17217 2011-01-19 06:29:08Z liubo $
*/

define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');
include_once(ROOT_PATH . 'includes/cls_transport.php');


$action = !empty($_REQUEST['action']) ? $_REQUEST['action'] : 'index';
if($action == 'submit_url'){
	if(isset($_POST['url']) and $_POST['url'] != ''){
		$url = $_POST['url'];
	}else{
		ecs_header("Location: taobao.php");
	}
	if(strstr($url,'tmall') !== FALSE){
   		$cacheid = save_tmall($url);
	}else{
		$cacheid = save_taobao($url);
	}
    
    ecs_header("Location: taobao.php?action=view&cacheid=$cacheid");
    
}elseif($action == 'insert'){
	if(isset($_POST['cacheid']) and $_POST['cacheid'] != ''){
		$cacheid = $_POST['cacheid'];
	}else{
		exit('cacheid is null');
	}
	
	if(isset($_POST['cat_id']) and $_POST['cat_id'] != ''
		and isset($_POST['goods_type']) and $_POST['goods_type'] != ''
		and isset($_POST['brand_id']) and $_POST['brand_id'] != ''
		and isset($_POST['price']) and $_POST['price'] != ''
	){
		$res = insert_product_by_cache($cacheid, $_POST['cat_id'], $_POST['goods_type'], $_POST['brand_id'], $_POST['price']);
		if($res == TRUE){
			ecs_header("Location: taobao.php?action=index&warning=" . urlencode('添加成功'));
		}else{
			die('faild');
		}
	}else{
		 ecs_header("Location: taobao.php?action=view&cacheid=$cacheid&warning=" . urlencode('分类，属性分类，品牌必选一个，价格必填一个'));
	}
	
}elseif($action == 'view'){
	if(isset($_GET['cacheid']) and $_GET['cacheid'] != ''){
		$cacheid = $_GET['cacheid'];
	}
	if(isset($_GET['warning']) and $_GET['warning'] != ''){
		$warning = urldecode($_GET['warning']);
	}
	$sql = ("select * from `cache` where `id` = $cacheid ");
	$cache = $db->getRow($sql);
	if($cache > 0 ){
		$goods_array = unserialize($cache['value']);

		if($goods_array !== FALSE){
			$smarty->assign('cacheid', $cacheid);
			$smarty->assign('ur_here', '淘宝商城商品采集器');
			$smarty->assign('url', $cache['name']);
			$smarty->assign('action', $action);
			
			$smarty->assign('goods', $goods_array);
			if($warning){
				$smarty->assign('warning', $warning);
			}
			$smarty->assign('goods_type_list', goods_type_list($goods['goods_type']));
			$smarty->assign('cat_list',     cat_list(0, $cat_id));
			$smarty->assign('brand_list',   get_brand_list());
			assign_query_info();
			$smarty->display('taobao.htm');
			
		}else{
			die('缓存内容错误');
		}
	}else{
		die('没找到该缓存');
	}

}elseif($action == 'index'){
	if(isset($_GET['warning']) and $_GET['warning'] != ''){
		$warning = urldecode($_GET['warning']);
		$smarty->assign('warning', $warning);
	}
	$smarty->assign('ur_here', '淘宝商城商品采集器');
	$smarty->assign('action', $action);
	assign_query_info();
	$smarty->display('taobao.htm');
}

/*
 * $cacheid 缓存表的id字段值
 * $cat_id 商品分类id
 * $attr_cat_id 商品分类属性id
 * $brand_id 品牌ID
 * $price  商品价格
 * 
 */
function insert_product_by_cache($cacheid, $cat_id, $attr_cat_id, $brand_id, $price){
	global $db,$ecs;
	$sql = ("select * from `cache` where `id` = $cacheid ");
	$good_row = $db->getRow($sql);
	
	$goods_sn = $good_row['name'];
	
	$sql = "SELECT COUNT(*) FROM " . $ecs->table('goods') .
	" WHERE goods_sn = '$goods_sn' AND is_delete = 0 ";
	if ($db->getOne($sql) > 0)
	{
		//sys_msg('已经有该产品', 1, array(), false);
		//die();
	}

	$good = unserialize($good_row['value']);

	//1.插入产品
	//正常价格 0.85
	//$price = $good['normal_price']*0.85;
	
	$goods_thumb = str_replace('_40x40', '_310x310', $good['thumb_pic'][0]);
	$goods_img = str_replace('_40x40', '_310x310', $good['thumb_pic'][0]);
	$original_img = str_replace('_40x40.jpg', '', $good['thumb_pic'][0]);
	

	
	$sql = "INSERT INTO `ecs_goods` (goods_name, goods_name_style, goods_sn, cat_id, brand_id, shop_price, market_price, is_promote, promote_price, promote_start_date, promote_end_date, goods_img, goods_thumb, original_img, keywords, goods_brief, seller_note, goods_weight, goods_number, warn_number, integral, give_integral, is_best, is_new, is_hot, is_on_sale, is_alone_sale, is_shipping, goods_desc, add_time, last_update, goods_type, rank_integral, suppliers_id)
	VALUES ('{$good['name']}', '', '{$goods_sn}', '{$cat_id}', '{$brand_id}', '{$price}', '{$good['normal_price']}', '0','0', '0', '0', '{$goods_img}', '{$goods_thumb}', '{$original_img}', '', '', '', '0', '1', '1', '5', '-1', '0', '0', '0', '1', '1', 0,
	'{$good['descript']}', '1336784233', '1336784233', {$attr_cat_id}, '-1', '0')";
	
	$db->query($sql);
	
	$good_id = $db->insert_id();
	
	//2插入属性
	if(isset($good['attributes'])){
		foreach ($good['attributes'] as $attribute){
			foreach ($attribute as $att_name => $att_value){
			
				//查找 该分类下 有没有该属性，
				//cat_id=1(衣服)	attr_name
				$row = $db->getRow("select `attr_id` from `ecs_attribute` where `cat_id` = {$attr_cat_id} and attr_name LIKE '$att_name'");
				if($att_name == '颜色分类' or $att_name == '颜色' or $att_name == '尺码'){
					$attr_type = 1;
				}else{
					$attr_type = 0;
				}
				//如果没有该属性 则插入该属性
				if($row === FALSE){
					$db->query("
					INSERT INTO  `ecs_attribute` (`attr_id` , `cat_id` , `attr_name` ,`attr_input_type` ,
					`attr_type` , `attr_values` , `attr_index` ,`sort_order` ,
					`is_linked` , `attr_group`)
					VALUES (NULL ,  '{$attr_cat_id}',  '$att_name',  '0',  $attr_type,  '',  '0',  '0',  '0',  '0')"
					);
					$attr_id = $db->insert_id();
				}else{
					$attr_id = $row['attr_id'];
				}
				
				if($attr_type == 1){
					$values = explode('&nbsp;', $att_value);
					foreach ($values as $one_att_value){
						if($one_att_value != ''){
							if(strtolower(mb_detect_encoding($one_att_value)) == 'ascii'){
								$one_att_value = mb_convert_encoding($one_att_value, 'UTF-8', 'HTML-ENTITIES');
							}	
							$sql = "INSERT INTO `ecs_goods_attr`(goods_attr_id,	goods_id, attr_id, attr_value)
							VALUES (NULL ,  $good_id,  $attr_id,  '$one_att_value')
							";
							
							$db->query($sql);
						}
					}

				}else{
					$att_value = str_replace('&nbsp;', '', $att_value);
					if(strtolower(mb_detect_encoding($att_value)) == 'ascii'){
						$att_value = mb_convert_encoding($att_value, 'UTF-8', 'HTML-ENTITIES');
					}
					$sql = "INSERT INTO `ecs_goods_attr`(goods_attr_id,	goods_id, attr_id, attr_value)
					VALUES (NULL ,  $good_id,  $attr_id,  '$att_value')
					";
					
					$db->query($sql);
				}
			}
		}
	}
	//3.插入图片相册
	foreach($good['thumb_pic'] as $key => $value){
		
		$goods_thumb = str_replace('_40x40', '_310x310', $value);
		$goods_img = str_replace('_40x40', '_310x310', $value);
		$original_img = str_replace('_40x40.jpg', '', $value);
			
		//$goods_thumb = save_image($goods_thumb);
		//$goods_img = save_image($goods_img);
		//$original_img =save_image($original_img);
			
		$sql= "INSERT INTO  `ecs_goods_gallery` (
				`img_id` , `goods_id` , `img_url` ,`img_desc` ,`thumb_url` ,`img_original`)
			VALUES (NULL ,  $good_id,  '$goods_img',  '',  '$goods_thumb',  '$original_img'
			);";
			
		$db->query($sql);
	}
	
	//4评论
	if(isset($good['comment'])){
		foreach ($good['comment'] as $key => $value){
			$time = strtotime(trim($value['rateDate']));
			if($time==''){
				$time = strtotime('2012-'.rand(1,5).'-'.rand(1,30).' '.rand(1,24).':'.rand(1,60).':'.rand(1,60));
			}
			
			$row = array(
					'comment_type'=>1,
					'id_value'=>$id,
					'email'=>rand(10000,9999999).'@qq.com',
					'user_name'=>$value['displayUserNick'],
					'content'=>'<span id="auctionSku">'.$value['auctionSku'].'</span>'.$value['rateContent'],
					'comment_rank'=>rand(3,5),
					'add_time'=>$time,
					'ip_address'=>'207.10.108.10',
					'status'=>1,
					'user_id'=>88,
			);
			
			$sql= "INSERT INTO  `ecs_comment` (
					`comment_type` , `id_value` , `email` ,`user_name` ,`content` ,`comment_rank`, `add_time`, `ip_address`, `status`, `user_id`)
				VALUES (1 ,  $good_id,  '".rand(10000,9999999)."@qq.com',  '".$value['displayUserNick']."',  '".'<span id="auctionSku">'.$value['auctionSku'].'</span>'.$value['rateContent']."',  ".rand(3,5)."
				,'$time','207.10.108.10',1,88);";
				
			$db->query($sql);
		}
	}
	return TRUE;
	
	
}

function save_tmall($url){
	global $db,$ecs;
	preg_match('/id\=([\d]*)/', $url , $id_match);
	$goods_sn = $id_match[1];
	//检查是否已经存在该产品
	$sql = ("select * from " . $ecs->table('goods') . " where `goods_sn` = $goods_sn ");
	$exist_p = $db->getRow($sql);
	if($exist_p > 0){
		print_r('已经有这个产品了,点击查看<a href="/goods.php?id='.$exist_p['goods_id'].'">'.$exist_p['goods_id'].'</a>');
		die('');
	}
	
	$transport = new transport();
	$transport->use_curl = true;
	//$transport->proxy = "web-proxy.oa.com:8080";
	
	if(!file_exists(ROOT_PATH.'data/transport_cookie')){
		fopen(ROOT_PATH.'data/transport_cookie', "w");
	}
	
	$transport->cookie_file = ROOT_PATH.'data/transport_cookie';
	
	$return = $transport->request($url);
	
	while(preg_match('/(Location:|URI:)(.*?)\n/', $return['header'], $matches)){
	
		$url = trim(array_pop($matches));
	
		$return = $transport->request($url);
	}
	
	$return = mb_convert_encoding($return['body'], 'UTF-8', 'GBK');
	
	
	$item_array = array();
	//匹配标题
	if(preg_match('/<title>(.*?)<\/title>/i', $return, $matchs)){
		$item_array['name'] = $matchs[1];
		$item_array['name'] = str_replace('-tmall.com', '', $item_array['name']);
		$item_array['name'] = str_replace('天猫', '', $item_array['name']);
	}else{
		//die('标题匹配错误， 地址:'.$addr);
	};
	
	//匹配标准价格
	if(preg_match('/<strong id\=\"J\_StrPrice\" >(.*)?<\/strong>/i', $return, $matchs)){
		$item_array['normal_price'] = $matchs[1];
	}else{
		//die('标准价格匹配错误， 地址:'.$addr);
	};
	
	//匹配图片
	if(preg_match('/tb\-thumb(.*)J\_ShareParam/is', $return, $matchs)){
		if(preg_match_all('/src\=\"([^"]*?)\"/is', $matchs[0], $matches)){
			$item_array['thumb_pic'] = $matches[1];
		}else{
			//die('图片匹配错误， 地址:'.$addr);
		};
	}else{
		//die('图片区域匹配错误， 地址:'.$addr);
	};
	
	//匹配描述
	if(preg_match('/http:\/\/dsc([^\']*)\'/is', $return, $matchs)){
		$des = $transport->request('http://dsc'.$matchs[1], '', 'GET', array('User-Agent', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.56 Safari/536.5'));
		$des = mb_convert_encoding($des['body'], 'UTF-8', 'GBK');
		$des = str_replace('var desc=', '', $des);
		$des = str_replace('\\', '', $des);
		$des = str_replace('\'', '', $des);
		$des = preg_replace('/([^<]*)</is', '', $des, 1);
		$des = preg_replace('/<td[^>]*>(.*?)<\/td>/is', '', $des);
	
		$des = preg_replace('/<tr[^>]*>(.*?)<\/tr>/is', '', $des);
		$des = preg_replace('/<a[^>]*><\/a>/is', '', $des);
		$des = preg_replace('/<table[^>]*>(.*?)<\/table>/is', '', $des);
		$des = str_replace('</td>', '', $des);
		$des = str_replace('</tr>', '', $des);
		$des = str_replace('</table>', '', $des);
		$des = str_replace('<p></p>', '', $des);
		$des = str_replace('http://img04.taobaocdn.com/imgextra/i4/392195157/T2qQeIXgdaXXXXXXXX_!!392195157.jpg', '', $des);
		$des = str_replace('http://img02.taobaocdn.com/imgextra/i2/392195157/T2QzmGXXJaXXXXXXXX_!!392195157.gif', '', $des);
		$des = str_replace('http://img03.taobaocdn.com/imgextra/i3/392195157/T2BkCIXbFXXXXXXXXX_!!392195157.jpg', '', $des);
		$des = str_replace('http://img03.taobaocdn.com/imgextra/i3/392195157/T2HByIXe0XXXXXXXXX_!!392195157.jpg', '', $des);
	
		$item_array['descript'] = '<'.$des;
	}else{
		//die('图片区域匹配错误， 地址:'.$addr);
	};
	
	//匹配属性
	if(preg_match('/<ul class\=\"attributes-list\">(.*?)<\/ul>/is', $return, $matchs)){
		if(preg_match_all('/<li[^>]*>(.*?)<\/li>/is', $matchs[0], $matches)){
			foreach ($matches[1] as $key => $value){
				$value = str_replace(':', '=', $value);
				$value = str_replace(':', '=', $value);
				$value = str_replace('：', '=', $value);
	
				list($att, $v) = explode("=", $value);
					
				$att = trim($att);
	
				$v = trim($v);
	
				$item_array['attributes'][$key] = array($att=>$v);
			}
		}else{
				
			//die('属性匹配错误， 地址:'.$addr);
		};
	}else{
		//die('属性区域匹配错误， 地址:'.$addr);
	};
	
	//品牌评论
	$m = preg_match('/data-reviewApi="(.*?)"/is', $return, $matches);
	
	if(count($matches) > 0){
		$comment = $transport->request($matches[1], '', 'GET', array('User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.56 Safari/536.5'));
	
		$comment = $comment['body'];
		$comment = mb_convert_encoding($comment, 'UTF-8', 'GBK');
		$comment = strstr($comment,'{');
		$comment_array = json_decode($comment, true);
		$item_array['comment'] = $comment_array['rateListInfo']['rateList'];
	}
	
	$dbcontent = serialize($item_array);
	
	$sql = "select * from `cache` where `name` = $goods_sn ";
	$cache_row = $db->getRow($sql);
	if($cache_row !== FALSE){
	
		$sql = "UPDATE `cache` set `value` = '$dbcontent' where `name` ={$goods_sn};";
		$db->query($sql);
		$cacheid = $cache_row['id'];
		 
	}else{
	
		$sql = "INSERT INTO `cache`(name,value) values('{$goods_sn}', '$dbcontent');";
		$db->query($sql);
		$cacheid = $db->insert_id();
		 
	}
	return $cacheid;	
}

function save_taobao($url){
	global $db,$ecs;
	preg_match('/id\=([\d]*)/', $url , $id_match);
	$goods_sn = $id_match[1];
	//检查是否已经存在该产品
	$sql = ("select * from " . $ecs->table('goods') . " where `goods_sn` = $goods_sn ");
	$exist_p = $db->getRow($sql);
	if($exist_p > 0){
		print_r('已经有这个产品了,点击查看<a href="/goods.php?id='.$exist_p['goods_id'].'">'.$exist_p['goods_id'].'</a>');
		die('');
	}
	
	$transport = new transport();
	$transport->use_curl = true;
	//$transport->proxy = "web-proxy.oa.com:8080";
	
	if(!file_exists(ROOT_PATH.'data/transport_cookie')){
		fopen(ROOT_PATH.'data/transport_cookie', "w");
	}
	
	$transport->cookie_file = ROOT_PATH.'data/transport_cookie';
	
	$return = $transport->request('http://item.taobao.com/item.htm?id=17516904071'
			,''
			, 'GET'
			, array('User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.56 Safari/536.5',
					'Cache-Control: max-age=0',
					));

	
	while(preg_match('/(Location:|URI:)(.*?)\n/', $return['header'], $matches)){
	
		$url = trim(array_pop($matches));
	
		$return = $transport->request($url);
	}
	
	$return = mb_convert_encoding($return['body'], 'UTF-8', 'GBK');
	
	
	$item_array = array();
	//匹配标题
	if(preg_match('/<title>(.*?)<\/title>/i', $return, $matchs)){
		$item_array['name'] = $matchs[1];
		$item_array['name'] = str_replace('-tmall.com', '', $item_array['name']);
		$item_array['name'] = str_replace('天猫', '', $item_array['name']);
	}else{
		//die('标题匹配错误， 地址:'.$addr);
	};
	
	//匹配标准价格
	if(preg_match('/<strong id\=\"J\_StrPrice\" >(.*)?<\/strong>/i', $return, $matchs)){
		$item_array['normal_price'] = $matchs[1];
	}else{
		//die('标准价格匹配错误， 地址:'.$addr);
	};
	
	
	//匹配图片
	if(preg_match('/tb\-thumb(.*)J\_ShareParam/is', $return, $matchs)){
		if(preg_match_all('/src\=\"([^"]*?)\"/is', $matchs[0], $matches)){
			$item_array['thumb_pic'] = $matches[1];
		}else{
			//die('图片匹配错误， 地址:'.$addr);
		};
	}else{
		if(preg_match('/J\_UlThumb(.*)collection\-btn/is', $return, $matchs)){
			if(preg_match_all('/src\=\"([^"]*?)\"/is', $matchs[0], $matches)){
				$item_array['thumb_pic'] = $matches[1];
			}else{
				//die('图片匹配错误， 地址:'.$addr);
			};
		}
		
		//die('图片区域匹配错误， 地址:'.$addr);
	};
	
	//匹配描述
	if(preg_match('/http:\/\/dsc([^\']*)\'/is', $return, $matchs)){
		$des = $transport->request('http://dsc'.$matchs[1], '', 'GET', array('User-Agent', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.56 Safari/536.5'));
		$des = mb_convert_encoding($des['body'], 'UTF-8', 'GBK');
		$des = str_replace('var desc=', '', $des);
		$des = str_replace('\\', '', $des);
		$des = str_replace('\'', '', $des);
		$des = preg_replace('/([^<]*)</is', '', $des, 1);
		$des = preg_replace('/<td[^>]*>(.*?)<\/td>/is', '', $des);
	
		$des = preg_replace('/<tr[^>]*>(.*?)<\/tr>/is', '', $des);
		$des = preg_replace('/<a[^>]*><\/a>/is', '', $des);
		$des = preg_replace('/<table[^>]*>(.*?)<\/table>/is', '', $des);
		$des = str_replace('</td>', '', $des);
		$des = str_replace('</tr>', '', $des);
		$des = str_replace('</table>', '', $des);
		$des = str_replace('<p></p>', '', $des);
		$des = str_replace('http://img04.taobaocdn.com/imgextra/i4/392195157/T2qQeIXgdaXXXXXXXX_!!392195157.jpg', '', $des);
		$des = str_replace('http://img02.taobaocdn.com/imgextra/i2/392195157/T2QzmGXXJaXXXXXXXX_!!392195157.gif', '', $des);
		$des = str_replace('http://img03.taobaocdn.com/imgextra/i3/392195157/T2BkCIXbFXXXXXXXXX_!!392195157.jpg', '', $des);
		$des = str_replace('http://img03.taobaocdn.com/imgextra/i3/392195157/T2HByIXe0XXXXXXXXX_!!392195157.jpg', '', $des);
	
		$item_array['descript'] = '<'.$des;
	}else{
		//die('图片区域匹配错误， 地址:'.$addr);
	};
	
	//匹配属性
	if(preg_match('/<ul class\=\"attributes-list\">(.*?)<\/ul>/is', $return, $matchs)){
		if(preg_match_all('/<li[^>]*>(.*?)<\/li>/is', $matchs[0], $matches)){
			foreach ($matches[1] as $key => $value){
				$value = str_replace(':', '=', $value);
				$value = str_replace(':', '=', $value);
				$value = str_replace('：', '=', $value);
	
				list($att, $v) = explode("=", $value);
					
				$att = trim($att);
	
				$v = trim($v);
	
				$item_array['attributes'][$key] = array($att=>$v);
			}
		}else{
	
			//die('属性匹配错误， 地址:'.$addr);
		};
	}else{
		//die('属性区域匹配错误， 地址:'.$addr);
	};
	
	//品牌评论
	$m = preg_match('/data-reviewApi="(.*?)"/is', $return, $matches);
	
	if(count($matches) > 0){
		$comment = $transport->request($matches[1], '', 'GET', array('User-Agent', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.56 Safari/536.5'));
	
		$comment = $comment['body'];
		$comment = mb_convert_encoding($comment, 'UTF-8', 'GBK');
		$comment = strstr($comment,'{');
		$comment_array = json_decode($comment, true);
		$item_array['comment'] = $comment_array['rateListInfo']['rateList'];
	}
	
	$dbcontent = serialize($item_array);
	
	$sql = "select * from `cache` where `name` = $goods_sn ";
	$cache_row = $db->getRow($sql);
	if($cache_row !== FALSE){
	
		$sql = "UPDATE `cache` set `value` = '$dbcontent' where `name` ={$goods_sn};";
		$db->query($sql);
		$cacheid = $cache_row['id'];
			
	}else{
	
		$sql = "INSERT INTO `cache`(name,value) values('{$goods_sn}', '$dbcontent');";
		$db->query($sql);
		$cacheid = $db->insert_id();
			
	}
	return $cacheid;
}
?>
